package com.block.datapush.form.item;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.datapush.form.enums.PushResultEnum;
import com.block.datapush.form.item.util.HappyTwoUtil;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

/**
 * 快乐分期
 */
@Service
public class HappyTwoPushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getPushLog();

    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) throws Exception {

        String queryUrl = formInfo.getQueryUrl();
        String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();
        String idnoMd5 = SecureUtil.md5(memberExtInfo.getIdCard()).toLowerCase();
        String NameMd5 = SecureUtil.md5(memberExtInfo.getUsername()).toLowerCase();

        Map<String, Object> bizParamMap = new HashMap<>();
        bizParamMap.put("name_md5", NameMd5);
        bizParamMap.put("idno_md5", idnoMd5);
        bizParamMap.put("phone_md5", mobileMd5);
        bizParamMap.put("age", memberExtInfo.getAge());
        bizParamMap.put("sex", memberExtInfo.getSex()==1?"男":"女");
        bizParamMap.put("ip", memberExtInfo.getReqIp());
        bizParamMap.put("working_city", memberExtInfo.getProvince()+"/"+memberExtInfo.getCity());
        bizParamMap.put("revenue", 8000);
        bizParamMap.put("salary_type", "银行代发");
        bizParamMap.put("loan_amount", HappyTwoUtil.getLoanAmount(memberExtInfo.getLoanAmount()));
        bizParamMap.put("loan_period", "12个月");
        bizParamMap.put("seniority", "在职6个月以上");
        bizParamMap.put("education", memberExtInfo.getXueli());
        bizParamMap.put("reserved_funds", HappyTwoUtil.getGjj(memberExtInfo.getGjj()));
        bizParamMap.put("social_security", HappyTwoUtil.getShebao(memberExtInfo.getSocialInsurance()));
        bizParamMap.put("credit_card", "无");
        bizParamMap.put("credit_record", HappyTwoUtil.getYuqi(memberExtInfo.getYuqi()));
        bizParamMap.put("insurance", HappyTwoUtil.getBaodan(memberExtInfo.getInsurance()));
        bizParamMap.put("real_estate", HappyTwoUtil.getHouse(memberExtInfo.getHouse()));
        bizParamMap.put("zhima", HappyTwoUtil.getZhima(memberExtInfo.getZhimaScore()));
        bizParamMap.put("car", HappyTwoUtil.getCar(memberExtInfo.getCar()));
        bizParamMap.put("loan_purpose", "消费");
        bizParamMap.put("industry","上班族");
        bizParamMap.put("loan_lately", "没有申请过贷款");


        String secretKey = memberExtInfo.getAppCode();

        String data = encrypt(JSON.toJSONString(bizParamMap), secretKey);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", data);


        log.info("【快乐分期】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【快乐分期】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");


        if (ObjectUtil.equal(code, 0)) {
            return true;
        }
        return false;
    }

    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject jsonObject) throws Exception {

        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);

        String queryUrl = formInfo.getRequestUrl();



        Map<String, Object> bizParamMap = new HashMap<>();
        bizParamMap.put("name",memberExtInfo.getUsername() );
        bizParamMap.put("idno", memberExtInfo.getIdCard());
        bizParamMap.put("phone", memberExtInfo.getMobile());
        bizParamMap.put("age", memberExtInfo.getAge());
        bizParamMap.put("sex", memberExtInfo.getSex()==1?"男":"女");
        bizParamMap.put("ip", memberExtInfo.getReqIp());
        bizParamMap.put("working_city", memberExtInfo.getProvince()+"/"+memberExtInfo.getCity());
        bizParamMap.put("revenue", 8000);
        bizParamMap.put("salary_type", "银行代发");
        bizParamMap.put("loan_amount", HappyTwoUtil.getLoanAmount(memberExtInfo.getLoanAmount()));
        bizParamMap.put("loan_period", "12个月");
        bizParamMap.put("seniority", "在职6个月以上");
        bizParamMap.put("education", memberExtInfo.getXueli());
        bizParamMap.put("reserved_funds", HappyTwoUtil.getGjj(memberExtInfo.getGjj()));
        bizParamMap.put("social_security", HappyTwoUtil.getShebao(memberExtInfo.getSocialInsurance()));
        bizParamMap.put("credit_card", "无");
        bizParamMap.put("credit_record", HappyTwoUtil.getYuqi(memberExtInfo.getYuqi()));
        bizParamMap.put("insurance", HappyTwoUtil.getBaodan(memberExtInfo.getInsurance()));
        bizParamMap.put("real_estate", HappyTwoUtil.getHouse(memberExtInfo.getHouse()));
        bizParamMap.put("zhima", HappyTwoUtil.getZhima(memberExtInfo.getZhimaScore()));
        bizParamMap.put("car", HappyTwoUtil.getCar(memberExtInfo.getCar()));
        bizParamMap.put("loan_purpose", "消费");
        bizParamMap.put("industry","上班族");
        bizParamMap.put("loan_lately", "没有申请过贷款");


        String secretKey = memberExtInfo.getAppCode();

        String data = encrypt(JSON.toJSONString(bizParamMap), secretKey);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", data);

        log.info("【快乐分期】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【快乐分期】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushResultDTO.setResult(result);
        pushResultDTO.setCode(String.valueOf(code));
        pushResultDTO.setMessage(msg);
        pushResultDTO.setParamContent(JSON.toJSONString(bizParamMap));
        if (ObjectUtil.equal(code, Integer.valueOf(0))) {
            pushResultDTO.setSuccess(true);
            pushResultDTO.setPushResult(PushResultEnum.SUCCESS.getType());
        } else {
            pushResultDTO.setPushResult(PushResultEnum.FAILED.getType());
            pushResultDTO.setSuccess(false);
        }
        return pushResultDTO;
    }

    private static String encrypt(String data, String secretKey) throws Exception {
        byte[] encrpyted = tripleDES(Cipher.ENCRYPT_MODE, data.getBytes(StandardCharsets.UTF_8), secretKey.getBytes());
        return new String(Base64.encodeBase64(encrpyted));
    }


    private static byte[] tripleDES(int opmode, byte[] data, byte[] secretKey) throws Exception {
        return cipher("DESede", "DESede/CBC/PKCS5Padding", opmode, data, "01234567".getBytes(), secretKey);
    }

    private static byte[] cipher(String algorithm, String transformation, int opmode, byte[] data, byte[] iv,
                                 byte[] secretKey) throws Exception {
        Key key = SecretKeyFactory.getInstance(algorithm).generateSecret(new DESedeKeySpec(secretKey));
        IvParameterSpec spec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(opmode, key, spec);
        return cipher.doFinal(data);
    }


    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }

}
